<template>
  <div id="score_summary" class="app-container">
    <div class="filter-container">
      <el-card shadow="hover">
        <el-row>
          <el-col :span="6">
            <span style="font-size: 14px; color: #606266;">姓名：</span>
            <el-input v-model="listQuery.realName" placeholder="姓名" style="width: 200px;" class="filter-item" />
          </el-col>
          <el-col :span="6">
            <span style="font-size: 14px; color: #606266;">学期：</span>
            <el-select v-model="listQuery.stageNum" placeholder="学期" style="width: 220px;" clearable class="filter-item">
              <el-option v-for="item in semesterOptions" :key="item.stage_num" :label="item.stage_num" :value="item.stage_num" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <span style="font-size: 14px; color: #606266;">年级组：</span>
            <el-select
              v-model="listQuery.partID"
              placeholder="请选择"
              style="width: 220px;"
              clearable
              class="filter-item"
            >
              <el-option
                v-for="(item, index) in grade_group"
                :key="index"
                :label="item.name"
                :value="item.deptId"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
              查询
            </el-button>
            <el-button v-waves class="filter-item" type="warning" icon="el-icon-folder-checked" @click="setScoreCycle">
              归档
            </el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <el-table
      v-loading="listLoading"
      :data="tableData"
      :height="tableHeight"
      border
      stripe
      style="width: 100%"
    >
      <el-table-column label="考评明细" align="center" width="100" type="expand">
        <template slot-scope="props">
          <el-table
            :data="[props.row]"
            border
            stripe
            style="width: 100%"
          >
            <el-table-column
              align="center"
              label="职业道德总分"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="checkOneScoreRecord('professionalEthics', scope.row)">{{ scope.row.professionalEthics / 100 }}</el-button>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="职业能力总分"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="checkOneScoreRecord('vocationalAbility', scope.row)">{{ scope.row.vocationalAbility / 100 }}</el-button>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="工作表现总分"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="checkOneScoreRecord('taskPerformance', scope.row)">{{ scope.row.taskPerformance / 100 }}</el-button>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="工作业绩总分"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="checkOneScoreRecord('performance', scope.row)">{{ scope.row.performance / 100 }}</el-button>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="突出贡献总分"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="checkOneScoreRecord('outstandingContribution', scope.row)">{{ scope.row.outstandingContribution / 100 }}</el-button>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="一票否决情况"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="checkOneScoreRecord('oneVote', scope.row)">
                  <i v-if="scope.row.oneVote > 0" class="el-icon-check" style="color: #F56C6C" />
                  <i v-else class="el-icon-close" style="color: #67C23A" />
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="selfCommit"
              label="自评">
            <template slot-scope="scope">
                {{ scope.row.otherCommit / 100 }}
              </template>
          </el-table-column>
            <el-table-column
              prop="otherCommit"
              align="center"
              label="他评">
            <template slot-scope="scope">
                {{ scope.row.otherCommit / 100 }}
              </template>
        </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="realName"
        label="姓名"
      />
      <el-table-column
        align="center"
        label="考评总分"
      >
        <template slot-scope="scope">
          {{ scope.row.fiveScoreSum / 100 }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="scoreSum"
        label="总分"
      >
      <template slot-scope="scope">
              {{ scope.row.scoreSum / 100 }}
            </template>
          
      </el-table-column>
    </el-table>

    <el-dialog
      :title="dialog_title"
      :visible.sync="dialogVisible"
      width="80%"
      top="5vh"
    >
      <el-table
        :data="dialogTableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="60"
        />
        <el-table-column
          prop="stage_num"
          label="考评学期"
          width="100"
        />
        <el-table-column
          prop="grade_item"
          label="成绩项"
        />
        <el-table-column
          width="100"
          label="提交总次数"
        >
         <template slot-scope="scope">
            {{ scope.row.count }}次
          </template>
        </el-table-column>

        <el-table-column
          label="总分和"
          width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.opt_flg + scope.row.sum / 100 }}分
          </template>
        </el-table-column>
        </el-table-column>

        <el-table-column
          label="总平均分"
          width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.opt_flg + scope.row.avg / 100 }}分
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!--    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />-->
  </div>
</template>

<script>
import { selectCycleGradeCount, getPart,selectSeekScoreRecord, selectAllScoreCycle, setScoreCycle } from '@/api/summaryMenu'
import { fetchList, fetchPersonalSummary, fetchPv, createArticle, updateArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Cookies from 'js-cookie'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: false,
      semesterOptions: [],
      listQuery: {
        realName: '',
        stageNum: ''
      },
      listQ: {
        'stage_num': '2021a',
        'effect_time_start': '2020-01-01',
        'effect_time_end': '2020-04-01',
        'userId': '13246678667'
      },
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      tableData: [],
      tableHeight: document.body.clientHeight - 230,
      dialogVisible: false,
      dialog_title: '打分明细',
      dialogTableData: [],
      grade_group: []
    }
  },
  created() {
    this.getList()
    this.getSelectAllScoreCycle()
    this.getPart()
  },
  methods: {
    headStyle() {
      return 'text-align:center'
    },
    checkOneScoreRecord(type, row) {
      let typeTitle = ''
      if (type == 'professionalEthics') {
        typeTitle = '职业道德总分'
      }
      if (type == 'vocationalAbility') {
        typeTitle = '职业能力总分'
      }
      if (type == 'taskPerformance') {
        typeTitle = '工作表现总分'
      }
      if (type == 'outstandingContribution') {
        typeTitle = '突出贡献总分'
      }
      if (type == 'oneVote') {
        typeTitle = '一票否决情况'
      }
      const params = {
        item: type,
        mobile: row.mobile,
        stageNum: this.listQuery.stageNum
      }
      selectSeekScoreRecord(params).then((res) => {
        if (res.code != '200') {
          this.$message({
            message: res.data.msg,
            type: 'warning'
          })
        } else {
          this.dialogTableData = res.data
          this.dialog_title = row.realName + '-' + typeTitle + '-打分明细'
          this.dialogVisible = true
        }
        this.listLoading = false
      }).catch(() => {

      })
    },
    getList() {
      this.listLoading = true
      selectCycleGradeCount(this.listQuery).then((res) => {
        if (res.code != '200') {
          this.$message({
            message: res.data.msg,
            type: 'warning'
          })
        } else {
          this.tableData = res.data
        }
        this.listLoading = false
      }).catch(() => {

      })
    },
    getTable() {
      fetchPersonalSummary(this.listQ).then(response => {
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        var personalSummaryData = new Array()
        for (const key in response.data) {
          const params = {
            'month': key,
            'morality': response.data[key]['职业道德'],
            'ability': response.data[key]['职业能力']
          }
          personalSummaryData.push(params)
        }
        this.tableData = personalSummaryData
        // this.$router.push({ path: '/auth-redirect?userId=' + this.total })
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDetails(row) {
    },
    handleMonthDetails(row) {
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    getSelectAllScoreCycle() {
      selectAllScoreCycle({}).then((res) => {
        if (res.code != '200') {
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        } else {
          this.semesterOptions = res.data
          for (let i = 0; i < this.semesterOptions.length; i++) {
            if (this.semesterOptions[i].valid_flg == 'Y') {
              this.listQuery.stageNum = this.semesterOptions[i].stage_num
            }
          }
        }
      }).catch(() => {

      })
    },
    getPart() {
      // eslint-disable-next-line no-undef 
      getPart().then((res) => {
        // eslint-disable-next-line eqeqeq
        if (res.code != '200') {
          console.log(res)
          this.$message({
            message: res.data.msg,
            type: 'warning'
          })
        } else {
          this.grade_group = res.data
          console.log(this.grade_group)
        }
        // eslint-disable-next-line indent
                }).catch(() => {

      })
    },
    setScoreCycle() {
      this.$confirm('此操作将归档本学期记录并开始新学期, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        setScoreCycle({}).then((res) => {
          if (res.code != '200') {
            this.$message({
              message: res.msg,
              type: 'warning'
            })
          } else {
            this.$message({
              message: res.msg,
              type: 'success'
            })
          }
        }).catch(() => {

        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消归档'
        })
      })
    }
  }
}
</script>

<style lang="scss">
  #score_summary {
    .el-table__expanded-cell[class*=cell] {
      padding: 20px;
    }
    .el-table th {
      background: #F5F7FA;
    }
    .el-table__expand-icon {
      color: #1890ff;
    }
  }
</style>
